package com.apotik.legenda.dao;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import org.hibernate.Criteria;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.apotik.legenda.model.Purchases;
import com.apotik.legenda.model.PurchasesItem;
import com.apotik.legenda.util.HibernateUtil;

public class PurchaseItemDao {

	public PurchaseItemDao() {
		// TODO Auto-generated constructor stub
	}
	
	public boolean saveOrUpdate(PurchasesItem obj){
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			//session.save(product);
			session.saveOrUpdate(obj);
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
			return false;
		}
	}
	
	public boolean delete(PurchasesItem obj){
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			
			session.beginTransaction();
			session.delete(obj);
			session.getTransaction().commit();
			session.close();
			
			return true;
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
			return false;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<PurchasesItem> listByPurchase(Purchases p){
		List<PurchasesItem> list = new ArrayList<>();
		
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			
			Criteria cr = session.createCriteria(PurchasesItem.class);
			cr.add(Restrictions.eq("purchase", p));
			cr.addOrder(Order.asc("purchasesItemId"));
			list = cr.list();
			
			session.close();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
		}
		
		return list;
	}
	
}
